import { _decorator, Component, Event, EventTouch, Node, NodeEventType, UITransform, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 摇杆脚本
 */
@ccclass('Joystick')
export class Joystick extends Component {

    /**
     * 摇杆中间的圆圈
     */
    @property(Node)
    private joystickCenterNd: Node;

    private uiTransfrom: UITransform;

    private maxR: number = 100;

    private changePos = new Vec3(0, 0, 0);

    start() {
        this.uiTransfrom = this.node.getComponent(UITransform);
        this.openTouchEvent();
    }

    openTouchEvent() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);

        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onTouchEnd(event: EventTouch) {
        console.log("onTouchEnd");
        this.joystickCenterNd.setPosition(0, 0);
        this.changePos.set(0, 0);
    }

    onTouchMove(event: EventTouch) {
        console.log("onTouchMove");
        //触摸移动时改变小球的位置
        const uiPos = event.getUILocation();
        const curPos = this.uiTransfrom.convertToNodeSpaceAR(v3(uiPos.x, uiPos.y, 0));
        const len = curPos.length();

        const scale = len > this.maxR ? this.maxR : len;
        const out = curPos.normalize().multiplyScalar(scale);
        this.joystickCenterNd.setPosition(out.x, out.y);

        //记录摇杆改变的位置
        this.changePos.set(out.x, out.y);
    }

    public get joyDir() {
        return this.changePos;
    }
}


